package com.shareyi.joywindow.sys.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.shareyi.fileutil.FileUtil;
import com.shareyi.joywindow.JoyWindowData;
import com.shareyi.joywindow.sys.domain.FileInfo;

public class AutoCodeFileUtil {
	
	private static final String CUR_DIR = "curDir:";
	static Logger logger=Logger.getLogger(AutoCodeFileUtil.class);
	
	public static List<FileInfo> getFileInfo(File[] files){
		if(files!=null && files.length>0){
			List<FileInfo> fileInfos=new ArrayList<FileInfo>(files.length);
			for (File file : files) {
				fileInfos.add(getFileInfo(file));
			}
			return fileInfos;
		}else{
			return Collections.EMPTY_LIST;
		}
		
	}

	
	private static FileInfo getFileInfo(File file) {
		FileInfo fileInfo=new FileInfo();
		fileInfo.setName(file.getName());
		fileInfo.setParentPath(file.getParent());
		fileInfo.setLastModified(file.lastModified());
		fileInfo.setIsHidden(file.isHidden());
		fileInfo.setCanWrite(file.canWrite());
		int fileType = 1;
		if(file.isDirectory()){
			fileType=2;
		}
		fileInfo.setFileType(fileType);
		return fileInfo;
		
	}
	
	
	
	/**
	 * 获取文件路径
	 * @param filePath
	 * @return
	 */
	public static String parseFilePath(String filePath){
		if(StringUtils.isEmpty(filePath)){
			return filePath;
		}
		String parsePath=filePath.trim();
		if(filePath.startsWith(CUR_DIR))
		{
			parsePath=filePath.substring(filePath.indexOf(":")+1).trim();
			parsePath=FileUtil.getRuntimeFilePath(parsePath);
		
		}else if(filePath.startsWith("baseDir:")){
			parsePath=filePath.substring(filePath.indexOf(":")+1).trim();
			parsePath=FileUtil.contactPath(JoyWindowData.getHttpServer().getBasePath(), parsePath);
		}else if(filePath.indexOf(":")==-1 && !filePath.startsWith("/")){ //既非linux绝对路径 也非Windows绝对路径 添加浅醉
			parsePath=FileUtil.getRuntimeFilePath( parsePath);
		}
		//如果为linux操作系统
		if(StringUtils.equals(File.separator,"/")){
			parsePath = parsePath.replaceAll("\\\\","/");
		}

		return parsePath;
	}


	/**
	 * 
	 * @param filePath
	 * @return
	 */
	public static String changeCurFilePath(String filePath) {
		if(StringUtils.isEmpty(filePath)){
			return filePath;
		}
		
		String runPath=FileUtil.getRunPath()+File.separator;
		
		logger.error("runPath="+runPath+", filePath="+filePath);
		if(filePath.startsWith(runPath)){
			if(runPath.length()==filePath.length()){
				return "";
			}
			return filePath.substring(runPath.length());
		}
		return filePath;
	}
	
}
